import 'package:flutter/material.dart';
import 'services/api_service.dart';
import 'models/models.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Encrypted Communication',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final ApiService _apiService = ApiService();
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _ageController = TextEditingController();
  final TextEditingController _phoneController = TextEditingController();

  String _result = '';
  bool _isLoading = false;
  List<UserData> _users = [];

  @override
  void initState() {
    super.initState();
    _usernameController.text = 'admin';
    _passwordController.text = 'password123';
  }

  void _setLoading(bool loading) {
    setState(() {
      _isLoading = loading;
    });
  }

  void _setResult(String result) {
    setState(() {
      _result = result;
    });
  }

  Future<void> _healthCheck() async {
    _setLoading(true);
    try {
      final result = await _apiService.healthCheck();
      _setResult('Health Check: ${result.toString()}');
    } catch (e) {
      _setResult('Health Check Error: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> _login() async {
    _setLoading(true);
    try {
      final result = await _apiService.login(
        _usernameController.text,
        _passwordController.text,
      );
      _setResult('Login Success: Token=${result.token}, UserID=${result.userId}, Name=${result.name}');
    } catch (e) {
      _setResult('Login Error: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> _getUser() async {
    _setLoading(true);
    try {
      final result = await _apiService.getUser();
      _setResult('User: ID=${result.id}, Name=${result.name}, Email=${result.email}, Age=${result.age}, Phone=${result.phone}');
    } catch (e) {
      _setResult('Get User Error: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> _getUsers() async {
    _setLoading(true);
    try {
      final result = await _apiService.getUsers();
      setState(() {
        _users = result;
      });
      _setResult('Users loaded: ${result.length} users');
    } catch (e) {
      _setResult('Get Users Error: $e');
    } finally {
      _setLoading(false);
    }
  }

  Future<void> _createUser() async {
    if (_nameController.text.isEmpty || _emailController.text.isEmpty) {
      _setResult('Please fill in name and email');
      return;
    }

    _setLoading(true);
    try {
      final user = UserData(
        id: 0,
        name: _nameController.text,
        email: _emailController.text,
        age: int.tryParse(_ageController.text) ?? 0,
        phone: _phoneController.text,
      );
      
      final result = await _apiService.createUser(user);
      _setResult('User Created: ID=${result.id}, Name=${result.name}, Email=${result.email}');
      
      // 清空输入框
      _nameController.clear();
      _emailController.clear();
      _ageController.clear();
      _phoneController.clear();
    } catch (e) {
      _setResult('Create User Error: $e');
    } finally {
      _setLoading(false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Encrypted Communication'),
        backgroundColor: Colors.blue,
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 健康检查按钮
            ElevatedButton(
              onPressed: _isLoading ? null : _healthCheck,
              child: const Text('Health Check'),
            ),
            
            const SizedBox(height: 16),
            
            // 登录部分
            const Text('Login:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            TextField(
              controller: _usernameController,
              decoration: const InputDecoration(labelText: 'Username'),
            ),
            TextField(
              controller: _passwordController,
              decoration: const InputDecoration(labelText: 'Password'),
              obscureText: true,
            ),
            ElevatedButton(
              onPressed: _isLoading ? null : _login,
              child: const Text('Login'),
            ),
            
            const SizedBox(height: 16),
            
            // 用户操作部分
            const Text('User Operations:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    onPressed: _isLoading ? null : _getUser,
                    child: const Text('Get User'),
                  ),
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: ElevatedButton(
                    onPressed: _isLoading ? null : _getUsers,
                    child: const Text('Get Users'),
                  ),
                ),
              ],
            ),
            
            const SizedBox(height: 16),
            
            // 创建用户部分
            const Text('Create User:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            TextField(
              controller: _nameController,
              decoration: const InputDecoration(labelText: 'Name'),
            ),
            TextField(
              controller: _emailController,
              decoration: const InputDecoration(labelText: 'Email'),
            ),
            TextField(
              controller: _ageController,
              decoration: const InputDecoration(labelText: 'Age'),
              keyboardType: TextInputType.number,
            ),
            TextField(
              controller: _phoneController,
              decoration: const InputDecoration(labelText: 'Phone'),
            ),
            ElevatedButton(
              onPressed: _isLoading ? null : _createUser,
              child: const Text('Create User'),
            ),
            
            const SizedBox(height: 16),
            
            // 结果显示
            const Text('Result:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            Container(
              height: 100,
              padding: const EdgeInsets.all(8),
              decoration: BoxDecoration(
                border: Border.all(color: Colors.grey),
                borderRadius: BorderRadius.circular(4),
              ),
              child: SingleChildScrollView(
                child: Text(
                  _isLoading ? 'Loading...' : _result,
                  style: const TextStyle(fontSize: 12),
                ),
              ),
            ),
            
            const SizedBox(height: 16),
            
            // 用户列表
            if (_users.isNotEmpty) ...[
              const Text('Users List:', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
              Expanded(
                child: ListView.builder(
                  itemCount: _users.length,
                  itemBuilder: (context, index) {
                    final user = _users[index];
                    return ListTile(
                      title: Text(user.name),
                      subtitle: Text('${user.email} | Age: ${user.age} | ${user.phone}'),
                      leading: CircleAvatar(
                        child: Text(user.id.toString()),
                      ),
                    );
                  },
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    _nameController.dispose();
    _emailController.dispose();
    _ageController.dispose();
    _phoneController.dispose();
    super.dispose();
  }
}
